package com.cloud.message.service;

import cn.hutool.json.JSONUtil;
import com.cloud.message.entity.SysImMessage;
import com.cloud.socket.WebSocketBuilder;
import com.cloud.utils.SpringUtils;
import com.cloud.utils.StringUtils;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * IM通信服务端
 *
 * @author yzj
 */
@Component
@ServerEndpoint(value = "/webSocket/imServer/{clientId}")
public class WebSocketIMServer {

    private static Logger logger = LoggerFactory.getLogger(WebSocketIMServer.class);

    public WebSocketIMServer() {
        logger.info("[IM服务端]启动成功");
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        try {
            WebSocketBuilder.SESSIONS.add(session);
            WebSocketBuilder.SESSION_POOL.put(clientId, session);
            logger.info("[IM消息]有新的连接,总数为:" + WebSocketBuilder.SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        try {
            WebSocketBuilder.SESSIONS.remove(session);
            logger.info("[IM消息]连接断开,总数为:" + WebSocketBuilder.SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        try {
            SysImMessage imMessage = JSONUtil.toBean(message, SysImMessage.class);
            if (StringUtils.isNotNull(imMessage)) {
                SpringUtils.getBean(ISysImMessageService.class).saveSysImMessage(imMessage);
            }
        } catch (Exception e) {
            logger.error("[IM消息]解析JSON消息失败:" + message);
        }
        logger.info("[IM消息]收到客户端消息:" + message);
    }

}

